import sun.nio.ch.DirectBuffer;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;

/**
 * Author :  Rocky
 * Date : 31/05/2017 22:05
 * Description :
 * Test :
 */
public class AsynchronousFileChannelTest {


    public static void main(String[] args) throws IOException, InterruptedException {

        long s = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            CountDownLatch latch = new CountDownLatch(1024 * 256);
            File file = new File("Test.Scala" + i);
            Path path = file.toPath();
            AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path,
                    StandardOpenOption.WRITE,
                    StandardOpenOption.READ,
                    StandardOpenOption.CREATE);

            for (int j = 0; j < 1024 * 256; j++) {
                ByteBuffer buffer4k = ByteBuffer.allocateDirect(4 * 1024);
                asynchronousFileChannel.write(buffer4k, j * 4 * 1024, buffer4k.position(), new CompletionHandler<Integer, Integer>() {
                    @Override
                    public void completed(Integer result, Integer attachment) {
                        ((DirectBuffer) buffer4k).cleaner().clean();
                        latch.countDown();
                    }

                    @Override
                    public void failed(Throwable exc, Integer attachment) {
                        System.out.println("异常");
                    }
                });
            }
            latch.await();
        }

        System.out.println((System.currentTimeMillis() - s) + "ms");

    }
}
